package com.cytech.cloudclinic.dialog;

import android.app.AlertDialog;
import android.app.Dialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.cytech.cloudclinic.R;
import com.cytech.cloudclinic.adapter.AddDrugTagAdapter;
import com.cytech.cloudclinic.adapter.BillDrugAdapter;
import com.cytech.cloudclinic.base.BaseBean;
import com.cytech.cloudclinic.base.BaseObserver;
import com.cytech.cloudclinic.bean.Acupoint;
import com.cytech.cloudclinic.bean.AddDrugTag;
import com.cytech.cloudclinic.bean.CustomGroupDrug;
import com.cytech.cloudclinic.bean.Drug;
import com.cytech.cloudclinic.bean.DrugToll;
import com.cytech.cloudclinic.bean.event.TollEvent;
import com.cytech.cloudclinic.bean.req.AddPrescription;
import com.cytech.cloudclinic.bean.req.PrescriptionToll;
import com.cytech.cloudclinic.utils.ConvertUtils;
import com.cytech.cloudclinic.utils.RequestWithViewUtils;
import com.google.gson.Gson;
import com.yechaoa.yutils.ToastUtil;
import com.yechaoa.yutils.YUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 处方收费
 */
public class BillTollDialog extends DialogFragment {
    @BindView(R.id.diglog_drug_number_rv)
    RecyclerView numberRv;
    @BindView(R.id.diglog_drug_list_rv)
    RecyclerView drugRv;
    @BindView(R.id.et_create_bill_now_price)
    TextView nowPriceEt;

    @BindView(R.id.tv_bill_list_price)
    TextView listPrice;
    @BindView(R.id.tv_bill_should_price)
    TextView shouldPrice;

    private List<Drug> mDrugSelectList;
    private BillDrugAdapter drugAdapter;

    private AddPrescription addPrescription;
    private String prescription_id;

    public BillTollDialog(AddPrescription addPrescription,String prescription_id) {
        Bundle bundle = new Bundle();
        bundle.putSerializable("prescription",addPrescription);
        bundle.putString("prescription_id",prescription_id);
        setArguments(bundle);
    }

    @Override
    public void onStart() {
        super.onStart();
        WindowManager.LayoutParams lp = getDialog().getWindow().getAttributes();
        lp.width = (int) (0.9 * YUtils.getScreenWidth());
        lp.height = (int) (0.8 * YUtils.getScreenHeight());
        getDialog().getWindow().setAttributes(lp);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        LayoutInflater inflater = getActivity().getLayoutInflater();
        View view = inflater.inflate(R.layout.dialog_create_bill, null);
        ButterKnife.bind(this, view);
        builder.setView(view);

        prescription_id = getArguments().getString("prescription_id");
        addPrescription = (AddPrescription) getArguments().getSerializable("prescription");


        initNumRv();
        initDrugRv();
        new Handler().post(new Runnable() {
            @Override
            public void run() {
                calculationPrice();
            }
        });
        return builder.create();
    }

    private void calculationPrice() {
        List<Drug> drugs = drugAdapter.getData();
        double totalPrice = 0;
        for(int i=0;i<drugs.size();i++){
            totalPrice += drugs.get(i).count *drugs.get(i).sub_price;
        }
        listPrice.setText(String.valueOf(totalPrice));
        shouldPrice.setText(String.valueOf(totalPrice));
    }

    @OnClick(R.id.dialog_create_bill_cancel)
    public void onClickCancel(View view) {
        dismiss();
    }

    @OnClick(R.id.dialog_create_bill_toll)
    public void onClickToll(View view) {
        //dismiss();
        List<Drug> drugList = drugAdapter.getData();
        PrescriptionToll toll = new PrescriptionToll();
        toll.prescription_id = prescription_id;
        for (int i=0;i<drugList.size();i++){
            DrugToll drugToll = new DrugToll();
            drugToll.drug_id = drugList.get(i).drug_id;
            drugToll.practical_price = drugList.get(i).practical_price;
            toll.drugs.add(drugToll);
        }
        prescriptionToll(toll);
    }

    //数字键盘
    private void initNumRv() {
        List<AddDrugTag> numberList = buildNumValue();
        AddDrugTagAdapter numberAdapter = new AddDrugTagAdapter(R.layout.item_add_drug_tag, numberList);
        numberRv.setLayoutManager(new GridLayoutManager(getActivity(), 3));
        numberRv.setAdapter(numberAdapter);

        numberAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                String value = numberAdapter.getItem(position).value;
                nowPriceEt.setText(ConvertUtils.getRealNumValue(value, nowPriceEt.getText().toString()));
            }
        });
    }

    private void initDrugRv() {
        mDrugSelectList = new ArrayList<>();
        List<CustomGroupDrug> drugList = addPrescription.drugs;
        for(int i=0;i<drugList.size();i++){
            List<Drug> childDrugs = drugList.get(i).list;
            if(childDrugs!=null&&childDrugs.size()>0){
                childDrugs.get(0).headTitle = i+1;
                mDrugSelectList.addAll(childDrugs);
            }
        }
        drugAdapter = new BillDrugAdapter(mDrugSelectList);
        drugRv.setLayoutManager(new LinearLayoutManager(getActivity()));
        drugRv.setAdapter(drugAdapter);
    }

    public List<AddDrugTag> buildNumValue() {
        List<AddDrugTag> numList = new ArrayList<>();
        numList.add(new AddDrugTag("1", false));
        numList.add(new AddDrugTag("2", false));
        numList.add(new AddDrugTag("3", false));
        numList.add(new AddDrugTag("4", false));
        numList.add(new AddDrugTag("5", false));
        numList.add(new AddDrugTag("6", false));
        numList.add(new AddDrugTag("7", false));
        numList.add(new AddDrugTag("8", false));
        numList.add(new AddDrugTag("9", false));
        numList.add(new AddDrugTag("0", false));
        numList.add(new AddDrugTag(".", false));
        numList.add(new AddDrugTag("清除", false));
        return numList;
    }


    public void prescriptionToll(PrescriptionToll toll) {
        RequestWithViewUtils.getInstance().addDisposable(RequestWithViewUtils.getInstance().apiServer.prescriptionToll(objectToRequestBody(toll)), new BaseObserver<BaseBean<List<Acupoint>>>(null, false) {
            @Override
            public void onSuccess(BaseBean<List<Acupoint>> o) {
                ToastUtil.showToast("收费成功");
                EventBus.getDefault().post(new TollEvent());
                dismiss();
            }

            @Override
            public void onError(String msg) {

            }
        });
    }

    protected RequestBody objectToRequestBody(Object object){
        String requestStr = new Gson().toJson(object);
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"),requestStr);
        return body;
    }
}
